/**
 * state parameter for layout in home page
 *
 * Param : sidebar.opened, visitedViews
 */

import { set, get } from '../utils/storage'

const app = {
  state: {
    accessToken: undefined,
    refreshToken: undefined,
    expireTime: 0,
    isCollapse: false, // 菜单展开
    theme: false, // 主题名 dark\light ..
    language: 2
  },
  mutations: {
    SET_ACCESS_TOKEN (state, val) {
      set('ACCESS_TOKEN', val)
      state.accessToken = val
    },
    SET_REFRESH_TOKEN (state, val) {
      set('REFRESH_TOKEN', val)
      state.refreshToken = val
    },
    SET_EXPIRE_TIME (state, val) {
      set('EXPIRE_TIME', val)
      state.expireTime = val
    },
    TOGGLE_COLLAPSE: (state) => {
      let collapse = !state.isCollapse
      set('sidebarStatus', collapse ? 'true' : 'false')
      state.isCollapse = collapse
    },
    SET_THEME: (state, val) => {
      set('theme', val)
      state.theme = val
    },
    /** init app state with theme, collapse, language */
    INIT_STATE: (state) => {
      let at = get('ACCESS_TOKEN')
      if (at) {
        state.accessToken = at
      }
      let ft = get('REFRESH_TOKEN')
      if (ft) {
        state.refreshToken = ft
      }
      let et = get('EXPIRE_TIME')
      if (et) {
        state.expireTime = et
      }
      // console.log(at, ft, et)
      state.collapsed = get('collapsed') === 'true'
      let t = get('theme')
      if (t) {
        state.theme = t
      }
      let l = get('language')
      if (l) {
        state.language = l
      }
    }
  },
  actions: {
    CHANGE_COLLAPSE_STATE: ({ commit }) => {
      commit('TOGGLE_COLLAPSE')
    },
    CHANGE_THEME_STATE: ({ commit, state }) => {
      let theme = state.theme
      let val = theme === 'dark' ? 'light' : 'dark'
      commit('SET_THEME', val)
    },
    SET_LOGIN_TOKEN ({ commit }, info) {
      commit('SET_ACCESS_TOKEN', info.access_token)
      commit('SET_REFRESH_TOKEN', info.refresh_token)
      const current = new Date()
      const expireTime = current.setTime(current.getTime() + 1000 * info.expires_in)
      commit('SET_EXPIRE_TIME', expireTime)
    },
    DEL_LOGIN_TOKEN ({ commit }) {
      commit('SET_ACCESS_TOKEN', undefined)
      commit('SET_REFRESH_TOKEN', undefined)
      commit('SET_EXPIRE_TIME', undefined)
    }
  },
  getters: {
    getAccessToken (state) {
      return state.accessToken
    },
    menuCollapse (state) {
      let collapse = state.isCollapse
      if (!collapse) {
        collapse = get('sidebarStatus') === 'true'
      }
      return collapse
    },
    isDarkTheme (state) {
      return state.theme === 'dark'
    }
  }
}

export default app
